import pytz, operator
from chicago.models import Subscription
from django.core.management.base import NoArgsCommand
from django.template.loader import render_to_string
from django.contrib.sites.models import Site
from django.core.mail import EmailMessage, send_mass_mail
from django.conf import settings


TZ = pytz.timezone(settings.TIME_ZONE)

class Command(NoArgsCommand):

    help = 'Do one pass through the subscribers list, send all mail.'
    
    def handle_noargs(self, **options):

        emails = []
        from_email = settings.DEFAULT_FROM_EMAIL
        current_site = Site.objects.get_current()
        subject = render_to_string('subscriber_email_subject.txt')
        subject = ''.join(subject.splitlines())
        for s in Subscription.objects.active():
            news = []
            # drill down for the feed items, i'm sure there's a better way.
            for rep in s.get_reps():
                for feedmap in rep.feeds.filter(feed__is_defunct=False):
                    for item in feedmap.feed.feeditem_set.filter(
                                    ignore=False)[:settings.REPSHEET_FEED_SLICE]:
                        # timestamp manipulation to TZ
                        d = item.date_modified.replace(tzinfo=pytz.utc)
                        item.date_modified = d.astimezone(TZ)
                        news.append(item)

            # sort according to date, trick from IRC #python.
            news.sort(key=operator.attrgetter('date_modified'),reverse=True)

            html_content = render_to_string(
                            'subscriber_email.html',
                            {'sub':s,
                             'news':news,
                             'site':current_site })

            msg = EmailMessage(subject, html_content, from_email, [s.email])
            msg.content_subtype = "html"  # Main content is now text/html
            msg.send()
